package middleware

import (
	"gitee.com/kordar/layuiadmin/admin/enums"
	model "gitee.com/kordar/layuiadmin/admin/models"
	"gitee.com/kordar/layuiadmin/admin/repository"
	"github.com/gin-gonic/gin"
	response "github.com/kordar/goframework_resp"
	jwt "github.com/kordar/gojwt"
	"github.com/spf13/cast"
)

func AdminAuth(repos *repository.AdminRepository) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		var ok bool
		if ok, _ = checkAccess(ctx, repos); !ok {
			response.Unauthorized(ctx, "", nil)
			ctx.Abort()
			return
		}

		// --------------------------

		ctx.Next()
		return
	}
}

func checkAccess(ctx *gin.Context, repos *repository.AdminRepository) (bool, model.SysAdmin) {

	tokenValue := ctx.GetHeader("Token")
	claims, err := jwt.ParseToken(tokenValue, enums.HmacSampleSecret)
	if err == nil {
		id := cast.ToInt64(claims["id"])
		if admin, err3 := repos.FindOne(id); err3 == nil {
			ctx.Set(enums.AdminKey, admin)
			return true, admin
		}
	}

	return false, model.SysAdmin{}
}
